﻿Imports System.Runtime.InteropServices
Imports FastColoredTextBoxNS
Imports System.Text.RegularExpressions

Public Class SystemSet
    '指定一个窗口的新父（在vb里使用：利用这个函数，vb可以多种形式支持子窗口。例如，可将控件从一个容器移至窗体中的另一个。用这个函数在窗体间移动控件是相当冒险的，但却不失为一个有效的办法。如真的这样做，请在关闭任何一个窗体之前，注意用SetParent将控件的父设回原来的那个）
    <DllImport("user32", EntryPoint:="SetParent", SetLastError:=False, _
    CharSet:=CharSet.Auto, ExactSpelling:=False, _
    CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function SetParent _
                      (ByVal hWndChild As Integer, _
                       ByVal hWndNewParent As Integer) As Integer
    End Function
    Dim RunVBScript As New MSScriptControl.ScriptControl
    Dim DataBaseSet As New ModifyAddress(False)
    Private Const DescriptionSql1 As String = "SELECT  * FROM  ::fn_listextendedproperty (null, 'user', 'dbo', 'table','"
    Private Const DescriptionSql2 As String = "', 'column', default)"
    Dim SetPagesIndex As Integer = -1
    '==============================设置代码编辑文本框样式
    Dim BlueStyle As TextStyle = New TextStyle(Brushes.Blue, Nothing, FontStyle.Regular)
    Dim BoldStyle As TextStyle = New TextStyle(Nothing, Nothing, FontStyle.Bold Or FontStyle.Underline)
    Dim GrayStyle As TextStyle = New TextStyle(Brushes.Gray, Nothing, FontStyle.Regular)
    Dim MagentaStyle As TextStyle = New TextStyle(Brushes.Magenta, Nothing, FontStyle.Regular)
    Dim GreenStyle As TextStyle = New TextStyle(Brushes.Green, Nothing, FontStyle.Italic)
    Dim BrownStyle As TextStyle = New TextStyle(Brushes.Brown, Nothing, FontStyle.Italic)
    Dim MaroonStyle As TextStyle = New TextStyle(Brushes.Maroon, Nothing, FontStyle.Regular)
    Dim SameWordsStyle As MarkerStyle = New MarkerStyle(New SolidBrush(Color.FromArgb(40, Color.Gray)))
    Dim lang As String = "VB"
#Region "构造函数"
    Public Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        InitStylesPriority()
    End Sub
    Public Sub New(ByVal SetIndex As Integer)

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        SetPagesIndex = SetIndex
    End Sub
#End Region
    Private Sub SystemSet_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetParent(DataBaseSet.Handle.ToInt32, SetPages.TabPages(0).Handle.ToInt32)
        DataBaseSet.Show()
        DataBaseSet.BackColor = Color.White
        DataBaseSet.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        DataBaseSet.WindowState = 2
        '=================加载已保存的数据格式
        LB_CodeList.Items.Clear()
        SaveDataFormat.Items.Clear()
        LB_SearchTable.Items.Clear()
        If SaveData.Setting IsNot Nothing Then
            For i = 0 To SaveData.Setting.Count - 1
                SaveDataFormat.Items.Add(SaveData.Setting(i).SaveName)
            Next
        End If
        If CheckData IsNot Nothing Then
            For i = 0 To CheckData.Count - 1
                LB_CodeList.Items.Add(CheckData.Item(i).CheckName)
            Next
        End If
        If SaveData.SearchTable IsNot Nothing Then
            For i = 0 To SaveData.SearchTable.Count - 1
                LB_SearchTable.Items.Add(SaveData.SearchTable.Item(i).TableName)
            Next
        End If
        Btn_AddCode.Enabled = False
        Btn_SaveCode.Enabled = False
        RunVBScript.Language = "VBScript"
        If SetPagesIndex >= 0 And SetPagesIndex < SetPages.TabPages.Count Then
            SetPages.SelectedIndex = SetPagesIndex
        End If
        ToolTip1.SetToolTip(TB_LoadDataVBS, "  1.必须是完整的函数过程；" & vbCrLf & "  2.函数有一个参数，参数类型为ArrayList；" & vbCrLf & "  3.函数返回值为字符型数据，并且以 | 符号分隔对应到数据表的每列数据；" & vbCrLf & "  4.返回值中数据段必须等于7。")
        ToolTip1.ToolTipTitle = "编码规则"
        ToolTip1.UseAnimation = True
        ToolTip1.ShowAlways = True
        ToolTip1.AutoPopDelay = 3000
        '  ToolTip1.AutomaticDelay = 1
        For i = 0 To SetPages.TabPages.Count - 1
            ChangeButtonFromFrm(SetPages.TabPages(i))
        Next
        CBCodeMode.Items.Add(EnumCodeMode.None.ToString())
        CBCodeMode.Items.Add(EnumCodeMode.VBScript.ToString)
        CBCodeMode.Items.Add(EnumCodeMode.JavaScript.ToString)
        CBCodeMode.SelectedIndex = 0
        TabPage2_Resize(Nothing, e)
    End Sub

    Private Sub Btn_Remove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Remove.Click
        If SaveDataFormat.SelectedIndex >= 0 And SaveDataFormat.SelectedIndex < SaveDataFormat.Items.Count Then
            Dim RemoveString As String = SaveDataFormat.Items.Item(SaveDataFormat.SelectedIndex)
            SaveDataFormat.Items.Remove(RemoveString)
            RemovedFormat.Items.Add(RemoveString)
        End If
    End Sub

    Private Sub Btn_Recoevry_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Recoevry.Click
        If RemovedFormat.SelectedIndex >= 0 And RemovedFormat.SelectedIndex < RemovedFormat.Items.Count Then
            Dim Tmp As String = RemovedFormat.Items.Item(RemovedFormat.SelectedIndex)
            RemovedFormat.Items.Remove(Tmp)
            SaveDataFormat.Items.Add(Tmp)
        End If
    End Sub

    Private Sub Btn_FormatSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_FormatSave.Click
        If RemovedFormat.Items.Count > 0 Then
            If SaveData.Setting IsNot Nothing Then
                With SaveData.Setting
                    Dim SC As Integer = .Count
                    Dim RC As Integer = RemovedFormat.Items.Count
                    Dim tmp As String, RemoveCount As Integer
                    For i = 0 To RC - 1
                        tmp = RemovedFormat.Items.Item(i).ToString
                        For j = 0 To SC - 1
                            If tmp.ToUpper = .Item(j).SaveName.ToUpper Then
                                .RemoveAt(j)
                                Form1.RemoveSetting(tmp)
                                RemoveCount += 1
                                Exit For
                            End If
                        Next
                    Next
                    If MsgBox("是否删除当前选中的数据格式多个数据！", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "询问") = MsgBoxResult.Yes Then
                        Form1.SaveSetting()
                        RemovedFormat.Items.Clear()
                        MsgBox("数据保存成功，共删除：" & RemoveCount & "条记录！", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "提示")
                    End If
                End With
            End If

        End If
    End Sub

    Private Sub Btn_RunCode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_RunCode.Click
        Dim Result As String, gCode As String
        Try
            With RunVBScript
                .Language = CBCodeMode.Text
                gCode = CheckCode_Script.Text
                .AddCode(gCode)
                Result = .Run(TB_CheckFunName.Text, TB_TestData.Text)
                If String.IsNullOrEmpty(Result) Then MessageBox.Show(Me, "脚本函数未返回值！", "脚本错误", MessageBoxButtons.OK, MessageBoxIcon.Error) : Return
                CheckLength.Text = Result.Length
                MsgBox("测试结果为：" + Result, MsgBoxStyle.Information, "提示")
                Btn_AddCode.Enabled = True
                Btn_SaveCode.Enabled = True
            End With
        Catch ex As Exception
            Btn_AddCode.Enabled = False
            Btn_SaveCode.Enabled = False
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "错误")
        End Try
    End Sub

    Private Sub Btn_AddCode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_AddCode.Click
        If String.IsNullOrEmpty(TB_CheckName.Text) Or String.IsNullOrEmpty(TB_CheckFunName.Text) Then MsgBox("校验方式名称和函数名称，不能为空！", MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "提示") : Return
        If IsNumeric(CheckLength.Text) = False Then MsgBox("校验码长度必须是数值型数据！", MsgBoxStyle.Critical, "提示") : Return
        If Val(CheckLength.Text) <= 0 Then MsgBox("校验码长度必须大于或等于1！", MsgBoxStyle.Critical, "提示") : Return
        Dim tmpCheckMode As New CheckMode
        tmpCheckMode.CheckName = TB_CheckName.Text
        tmpCheckMode.CheckFunName = TB_CheckFunName.Text
        tmpCheckMode.CheckLength = CheckLength.Text
        tmpCheckMode.CheckDescription = CheckDescription.Text
        If CBCodeMode.Text.ToLower = "javascript" Then
            tmpCheckMode.CodeMode = EnumCodeMode.JavaScript
        ElseIf CBCodeMode.Text.ToLower = "vbscript" Then
            tmpCheckMode.CodeMode = EnumCodeMode.VBScript
        Else
            MessageBox.Show(Me, "校验码脚本类型必须为VBScript或者JavaScript!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return
        End If
        If CheckData IsNot Nothing Then
            For i = 0 To CheckData.Count - 1
                If tmpCheckMode.CheckName.ToUpper = CheckData.Item(i).CheckName.ToUpper Then MsgBox("校验方式已经存在，请确定是否已经添加过此校验方式！", MsgBoxStyle.Critical, "错误") : Return
                If tmpCheckMode.CheckFunName.ToUpper = CheckData.Item(i).CheckFunName.ToUpper Then MsgBox("校验方式函数名重复，请修改校验方式函数名！", MsgBoxStyle.Critical, "错误") : Return
            Next
        End If
        '  tmpCheckMode.CheckCode = getCheckFunction()
        tmpCheckMode.CheckCode = CheckCode_Script.Text
        If SaveData.CheckNumberMode IsNot Nothing Then
            SaveData.CheckNumberMode.Add(tmpCheckMode)
        Else
            SaveData.CheckNumberMode = New List(Of CheckMode)
            SaveData.CheckNumberMode.Add(tmpCheckMode)
        End If
        LB_CodeList.Items.Add(tmpCheckMode.CheckName)
        Form1.SaveSetting()
        Form1.ReLoadCheckMode()
        MsgBox("【" & tmpCheckMode.CheckName & "】校验方式已经保存，请先测试准确后再使用！", MsgBoxStyle.Information, "提示")
    End Sub
    Private Function getCheckFunction() As String
        Dim FunName As String = TB_CheckFunName.Text
        Dim FunCode As String = CheckCode_Script.Text
        Dim LinesCode() As String, tmpName As String = "", NameExist As Boolean = False
        Dim EndCode As Boolean = False, Param As String = ""
        Dim StartLine As Integer = 0, EndLine As Integer = 0
        Dim Result As String = "", CodeStartLine As Integer = -1, TmpCode As String
        LinesCode = FunCode.Split(vbCrLf)
        For i = 0 To LinesCode.Length - 1
            TmpCode = LinesCode(i).Trim
            If String.IsNullOrEmpty(TmpCode) = False And CodeStartLine < 0 Then CodeStartLine = i
            If InStr(TmpCode.ToUpper, "function ".ToUpper) > 0 Then
                Dim a As Integer = TmpCode.IndexOf("(")
                Dim c As Integer = TmpCode.IndexOf(")")
                Dim b As Integer = TmpCode.ToUpper.IndexOf("function ".ToUpper)
                If a > 8 Then
                    tmpName = TmpCode.Substring(b + 9, a - b - 9).Trim
                    If b - a + 1 > 0 Then Param = TmpCode.Substring(a + 1, b - a + 1)
                    StartLine = i
                    NameExist = True
                End If
            End If
            If InStr(TmpCode.ToUpper, "end ".ToUpper) > 0 And (InStr(TmpCode.ToUpper, " function".ToUpper)) > 0 Then
                If TmpCode.Replace(" ", "").ToUpper.Trim = "endfunction".ToUpper Then
                    EndCode = True
                    EndLine = i
                    Exit For
                End If
            End If
        Next
        ' MsgBox(CodeStartLine & "|" & StartLine)
        ' If NameExist And EndCode Then If Param = "" Or Param.IndexOf(",") >= 0 Then MsgBox("参数和校验需求不匹配！" & Param, MsgBoxStyle.Critical, "错误") : Return ""
        'If NameExist = False Or EndCode = False Then MsgBox("函数过程不完整！", MsgBoxStyle.Critical, "编码错误") : Return ""
        If NameExist And EndCode Then
            If FunName.ToUpper.Trim <> tmpName.ToUpper.Trim And StartLine = CodeStartLine Then Throw New Exception("函数名与设定不匹配，请重新输入函数名！" & FunName & "|" & tmpName) : Return ""
            If FunName.ToUpper.Trim = tmpName.ToUpper.Trim And String.IsNullOrEmpty(FunName) = True Then Throw New Exception("未设置函数名，请修改源码和设置！") : Return ""
        End If
        If CodeStartLine <> StartLine And StartLine > CodeStartLine Then
            Result = "function " & FunName & "(a)"
            For i = 0 To StartLine - 1
                Result = Result & vbCrLf & LinesCode(i)
            Next
            Result = Result & vbCrLf & "end function"
            For i = StartLine To LinesCode.Length - 1
                Result = Result & vbCrLf & LinesCode(i)
            Next
            Return Result
        Else
            If EndLine > StartLine Then
                For i = 0 To LinesCode.Length - 1
                    If Result <> "" Then
                        Result = Result & vbCrLf & LinesCode(i)
                    Else
                        Result = LinesCode(i)
                    End If
                Next
                Return Result
            Else
                Return "function " & FunName & "(a)" & vbCrLf & FunCode & vbCrLf & "end function"
            End If
        End If
    End Function

    Private Sub Btn_SaveCode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_SaveCode.Click
        Dim tmp As String = TB_CheckName.Text
        Dim sc As String = TB_CheckFunName.Text
        Dim ObjIndex As Integer = -1, ModyfyCheck As CheckMode
        If SaveData.CheckNumberMode IsNot Nothing Then
            For i = 0 To SaveData.CheckNumberMode.Count - 1
                With SaveData.CheckNumberMode
                    If .Item(i).CheckName.ToUpper = tmp.ToUpper And .Item(i).CheckFunName.ToUpper = sc.ToUpper Then
                        ObjIndex = i
                        ModyfyCheck = .Item(i)
                    End If
                End With
            Next
        End If
        If ObjIndex >= 0 Then
            With ModyfyCheck
                .CheckName = TB_CheckName.Text
                .CheckLength = CheckLength.Text
                .CheckFunName = TB_CheckFunName.Text
                .CheckDescription = CheckDescription.Text
                .CheckCode = CheckCode_Script.Text
                If (.CodeMode.ToString() <> CBCodeMode.Text()) Then MessageBox.Show(Me, "不能修改脚本代码类型，如需修改代码类型请重新添加!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) : Return
                If CBCodeMode.Text.ToLower = "JavaScript".ToLower Then
                    .CodeMode = EnumCodeMode.JavaScript
                ElseIf CBCodeMode.Text.ToLower = "VBScript".ToLower Then
                    .CodeMode = EnumCodeMode.VBScript
                Else
                    MessageBox.Show(Me, "校验码脚本类型必须为VBScript或者JavaScript!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return
                End If
            End With
            SaveData.CheckNumberMode.Item(ObjIndex) = ModyfyCheck
            Form1.SaveSetting()
            MsgBox("【" & ModyfyCheck.CheckName & "]校验方式修改成功，请注意测试校验方式的准确性！", MsgBoxStyle.Information, "提示")
        Else
            MsgBox("当前选中校验方式为系统内置函数不能修改！", MsgBoxStyle.Information, "提示")
        End If
    End Sub

    Private Sub LB_CodeList_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles LB_CodeList.DoubleClick
        Try
            Dim SelectedString As String = LB_CodeList.Items.Item(LB_CodeList.SelectedIndex)
            Dim selectedMode As CheckMode = Nothing
            If String.IsNullOrEmpty(SelectedString) = False Then
                For i = 0 To CheckData.Count - 1
                    If SelectedString.ToUpper = CheckData.Item(i).CheckName.ToUpper Then
                        selectedMode = CheckData.Item(i)
                        Exit For
                    End If
                Next
            End If
            Try
                With selectedMode
                    TB_CheckName.Text = .CheckName
                    TB_CheckFunName.Text = .CheckFunName
                    CheckDescription.Text = .CheckDescription
                    If .CodeMode <> EnumCodeMode.None Then
                        CBCodeMode.SelectedIndex = .CodeMode
                    Else
                        CBCodeMode.SelectedIndex = 0
                        CheckDescription.Text = "内置函数"
                    End If
                    CheckCode_Script.Text = .CheckCode
                    CheckLength.Text = .CheckLength
                    '  If Not (String.IsNullOrEmpty(.CheckCode)) Then CheckCode_Script.FreshString()
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "错误")
            End Try
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "错误")
        End Try
    End Sub

    Private Sub LB_CodeList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LB_CodeList.SelectedIndexChanged

    End Sub

    Private Sub Btn_CheckDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_CheckDel.Click
        Dim tmp As String = TB_CheckName.Text
        Dim sc As String = TB_CheckFunName.Text
        Dim ObjIndex As Integer = -1, ModyfyCheck As CheckMode
        If SaveData.CheckNumberMode IsNot Nothing Then
            For i = 0 To SaveData.CheckNumberMode.Count - 1
                With SaveData.CheckNumberMode
                    If .Item(i).CheckName.ToUpper = tmp.ToUpper And .Item(i).CheckFunName.ToUpper = sc.ToUpper Then
                        ObjIndex = i
                        ModyfyCheck = .Item(i)
                    End If
                End With
            Next
        End If
        If ObjIndex >= 0 Then
            If MsgBox("是否删除当前选中的校验方式【" & tmp & "】？", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "询问") = MsgBoxResult.Yes Then
                SaveData.CheckNumberMode.RemoveAt(ObjIndex)
                For i = LB_CodeList.Items.Count - 1 To 0 Step -1
                    If LB_CodeList.Items.Item(i).ToString.ToUpper = tmp.ToUpper Then LB_CodeList.Items.RemoveAt(i)
                Next
                Form1.SaveSetting()
                ClearAllText(TB_CheckFunName.Parent)
                MsgBox("数据删除成功！", MsgBoxStyle.Information, "提示")
            End If
        Else
            MsgBox("该校验方式为系统内置函数不能删除！", MsgBoxStyle.Information, "提示")
        End If
    End Sub
    Private Sub ClearAllText(ByVal Parent As Control)
        Dim tp As Type
        For Each item As Object In Parent.Controls
            tp = item.GetType
            If tp.ToString.ToUpper = "System.Windows.Forms.TextBox".ToUpper Then
                item.text = ""
            End If
        Next
    End Sub
    Private Sub Btn_DataBaseAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_DataBaseAdd.Click
        Dim TableName As String = TB_SearchTable.Text
        If String.IsNullOrEmpty(TB_SearchTable.Text) Then MsgBox("搜索数据的表明不能为空！", MsgBoxStyle.Critical, "错误") : Return
        If String.IsNullOrEmpty(TB_LoadDataSql.Text) Then MsgBox("加载数据库的Sql语句不能为空！", MsgBoxStyle.Critical, "错误") : Return
        If String.IsNullOrEmpty(TB_SearchSql.Text) Then MsgBox("搜索数据库的Sql语句不能为空！", MsgBoxStyle.Critical, "错误") : Return
        If String.IsNullOrEmpty(TB_LoadDataVBS.Text) Then MsgBox("加载数据到生产数据显示表的VBS脚本代码不能为空，在添加前最好先测试代码！", MsgBoxStyle.Critical, "错误") : Return
        If SaveData.SearchTable IsNot Nothing Then
            For i = 0 To SaveData.SearchTable.Count - 1
                If SaveData.SearchTable.Item(i).TableName.ToUpper = TableName.ToUpper And SaveData.DataBase.ToUpper = SaveData.SearchTable.Item(i).DataBaseName.ToUpper Then
                    MsgBox("要搜索的数据库表已经存在，请选择其他表！", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "提示") : Return
                End If
            Next
        End If
        Dim tmpData As New SearchData
        With tmpData
            .DataBaseName = SaveData.DataBase
            .TableName = TableName
            .SearchSql = TB_SearchSql.Text
            .LoadDataVBS = TB_LoadDataVBS.Text
            .DownLoadDataSql = TB_LoadDataSql.Text
            .DescriptionSql = TB_DescriptionSql.Text
        End With
        If SaveData.SearchTable Is Nothing Then SaveData.SearchTable = New List(Of SearchData)
        SaveData.SearchTable.Add(tmpData)
        LB_SearchTable.Items.Add(tmpData.TableName)
        Form1.SaveSetting()
        MsgBox("数据保存成功！", MsgBoxStyle.Information, "提示")
    End Sub

    Private Sub Btn_DataBaseRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_DataBaseRun.Click
        ' ClearAllText(Btn_DataBaseRun.Parent)

        Try
            RunVBScript.AddCode(TB_LoadDataVBS.Text)
            RunVBScript.Run(getVbsSubOrFunName(TB_LoadDataVBS.Text))
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub LB_SearchTable_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles LB_SearchTable.DoubleClick
        Dim tmp As String
        Dim tmpData As New SearchData
        Try
            tmp = LB_SearchTable.Items.Item(LB_SearchTable.SelectedIndex).ToString
            If SaveData.SearchTable IsNot Nothing Then
                For i = 0 To SaveData.SearchTable.Count - 1
                    If SaveData.SearchTable.Item(i).TableName.ToUpper = tmp.ToUpper Then
                        tmpData = SaveData.SearchTable.Item(i)
                    End If
                Next
            End If

            With tmpData
                ' .DataBaseName = SaveData.DataBase
                TB_SearchTable.Text = .TableName
                TB_SearchSql.Text = .SearchSql
                TB_LoadDataVBS.Text = .LoadDataVBS
                TB_LoadDataSql.Text = .DownLoadDataSql
                TB_DescriptionSql.Text = .DescriptionSql
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "错误")
        End Try
    End Sub

    Private Sub LB_SearchTable_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LB_SearchTable.SelectedIndexChanged

    End Sub

    Private Sub TB_SearchTable_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TB_SearchTable.TextChanged
        TB_DescriptionSql.Text = DescriptionSql1 + TB_SearchTable.Text + DescriptionSql2
        If String.IsNullOrEmpty(TB_LoadDataVBS.Text) Then
            TB_LoadDataVBS.AppendText("Function " & TB_SearchTable.Text & "(Param,TB_Prefix,TB_Suffix)")
            TB_LoadDataVBS.AppendText(vbCrLf & vbCrLf & "End Function")
        Else
            TB_LoadDataVBS.Text = ChangeFunName(TB_LoadDataVBS.Text, TB_SearchTable.Text)
        End If
    End Sub

    Private Sub Btn_SearchData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_SearchData.Click
        Dim tmpName As String = TB_SearchTable.Text
        Dim TmpData As New SearchData
        If SaveData.SearchTable IsNot Nothing Then
            With SaveData.SearchTable
                For i = 0 To .Count - 1
                    If tmpName.ToUpper = .Item(i).TableName.ToUpper Then
                        If MsgBox("是否修改该表搜索下载数据的设置？", MsgBoxStyle.Question + MsgBoxStyle.OkCancel, "询问") = MsgBoxResult.Ok Then
                            TmpData.TableName = TB_SearchTable.Text
                            TmpData.SearchSql = TB_SearchSql.Text
                            TmpData.LoadDataVBS = TB_LoadDataVBS.Text
                            TmpData.DownLoadDataSql = TB_LoadDataSql.Text
                            TmpData.DescriptionSql = TB_DescriptionSql.Text
                            TmpData.DataBaseName = SaveData.DataBase
                            .Item(i) = TmpData
                            Form1.SaveSetting()
                            MsgBox("修改数据保存成功！", MsgBoxStyle.Information, "提示")
                        End If
                    End If
                Next
            End With
        End If
    End Sub

    Private Sub TB_LoadDataVBS_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        ToolTip1.Show("  1.必须是完整的函数过程；" & vbCrLf & "  2.函数有一个参数，参数类型为ArrayList；" & vbCrLf & "  3.函数返回值为字符型数据，并且以 | 符号分隔对应到数据表的每列数据；" & vbCrLf & "  4.返回值中数据段必须等于7。", Me)
    End Sub
    Private Function ChangeFunName(ByVal Code As String, ByVal Name As String) As String
        Dim fun() As String
        Dim Value As String = ""
        Dim Fstart As Boolean = False
        Dim Parame As String = "", EndCode As Boolean = False
        Dim NR As Boolean = False
        fun = Strings.Split(Code, vbCrLf)
        For i = 0 To fun.Length - 1
            '  If fun(i).Trim <> "" Then
            If InStr(fun(i).ToUpper, "Function ".ToUpper) > 0 Then
                Fstart = True
                Dim a As Integer = fun(i).IndexOf("(")
                Dim b As Integer = fun(i).IndexOf(")")
                If b - a > 1 Then
                    Parame = fun(i).Substring(a + 1, b - a - 1)
                    Dim n() As String = Parame.Split(",")
                    If n.Length <> 3 Then Parame = "Param,TB_Prefix,TB_Suffix"
                Else
                    Parame = "Param,TB_Prefix,TB_Suffix"
                End If
                If String.IsNullOrEmpty(Value) Then
                    Value = "Function " & Name & "(" & Parame & ")"
                Else
                    Value += vbCrLf & "Function " & Name & "(" & Parame & ")"
                End If
            ElseIf fun(i).ToUpper.IndexOf("End ".ToUpper) < 0 And fun(i).ToUpper.IndexOf(" Function".ToUpper) < 0 Then
                If String.IsNullOrEmpty(Value) Then
                    Value = fun(i)
                Else
                    Value += vbCrLf & fun(i)
                End If
                If fun(i).Trim <> "" Then
                    NR = True
                End If
                EndCode = False
            ElseIf fun(i).ToUpper.IndexOf("End ".ToUpper) >= 0 And fun(i).ToUpper.IndexOf(" Function".ToUpper) > 0 Then
                If NR = True Then
                    Value += vbCrLf & fun(i)
                Else
                    Value += vbCrLf & vbCrLf & "'在此处添加函数内容" & vbCrLf & fun(i)
                End If
                EndCode = True
            End If
        Next
        If EndCode = False Then
            If NR = False Then
                Value += vbCrLf & vbCrLf & "'在此处添加函数内容" & vbCrLf & "End Function"
            End If
        End If
        Return Value
    End Function

    Private Sub Btn_ModyfyFormat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_ModyfyFormat.Click
        Dim tmp As String
        If SaveDataFormat.SelectedIndex < 0 Then
            MsgBox("请先选中要修改保存名称的数据！", MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, "提示")
            Return
        Else
            tmp = SaveDataFormat.Items.Item(SaveDataFormat.SelectedIndex)
            Dim SC As Integer = SaveData.Setting.Count - 1, FindIndex As Integer = -1
            Dim FindData As SaveSetting = Nothing, HasFind As Boolean = False
            For i = 0 To SC
                If tmp.ToUpper = SaveData.Setting(i).SaveName.ToUpper Then
                    FindIndex = i
                    FindData = SaveData.Setting(i)
                    Exit For
                End If
            Next
            If FindIndex >= 0 Then
                Dim ModifyName As String = ShowInput(Me, "请输入修改内容", FindData.SaveName, False)
                Dim HasExist As Boolean = False
                If String.IsNullOrEmpty(ModifyName) Then Return
                If ModifyName <> "" Then
                    For i = 0 To SC
                        If ModifyName.ToUpper = SaveData.Setting(i).SaveName.ToUpper Then
                            HasExist = True
                            Exit For
                        End If
                    Next
                End If
                If HasExist Then
                    MsgBox("输入的内容已经存在，请重新输入！", MsgBoxStyle.Information, "提示")
                Else
                    FindData.SaveName = ModifyName
                    SaveData.Setting(FindIndex) = FindData
                    SaveDataFormat.Items.Item(SaveDataFormat.SelectedIndex) = FindData.SaveName
                    Form1.SaveSetting()
                    Form1.ModifySetting(tmp, FindData.SaveName)
                    MsgBox("数据修改成功！", MsgBoxStyle.Information, "提示")
                End If
            End If
        End If
    End Sub

    Private Sub Btn_DeleteTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_DeleteTable.Click
        Dim tmp As String = ""
        Try
            tmp = LB_SearchTable.Items.Item(LB_SearchTable.SelectedIndex)
        Catch
        End Try
        If LB_SearchTable.SelectedIndex < 0 Then MsgBox("请先选择要删除的数据表！", MsgBoxStyle.Information, "提示") : Return
        For i = 0 To SaveData.SearchTable.Count - 1
            If tmp.ToUpper = SaveData.SearchTable.Item(i).TableName.ToUpper Then
                LB_SearchTable.Items.Remove(tmp)
                SaveData.SearchTable.RemoveAt(i)
                MsgBox("数据表已从本地删除成功！", MsgBoxStyle.OkOnly, "提示")
                Return
            End If
        Next
    End Sub

    Private Sub TabPage2_Resize(sender As Object, e As EventArgs) Handles TabPage2.Resize
        SaveDataFormat.Width = (TabPage2.Width - 85) / 2
        RemovedFormat.Width = (TabPage2.Width - 85) / 2 - 5
        RemovedFormat.Left = TabPage2.Width - RemovedFormat.Width
        SaveDataFormat.Height = TabPage2.Height - SaveDataFormat.Top
        RemovedFormat.Height = TabPage2.Height - RemovedFormat.Top
        Label2.Left = RemovedFormat.Left
        Btn_Remove.Left = SaveDataFormat.Width + SaveDataFormat.Left + 5
        Btn_ModyfyFormat.Left = Btn_Remove.Left
        Btn_Recoevry.Left = Btn_Remove.Left
        Btn_FormatSave.Left = Btn_Remove.Left
    End Sub

    Private Sub CBCodeMode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CBCodeMode.SelectedIndexChanged
        CheckCode_Script.ClearStylesBuffer()
        CheckCode_Script.Range.ClearStyle(StyleIndex.All)
        InitStylesPriority()
        If (CBCodeMode.SelectedIndex = 0) Then
            CheckCode_Script.Language = FastColoredTextBoxNS.Language.VB
        Else
            CheckCode_Script.Language = FastColoredTextBoxNS.Language.CSharp
        End If

    End Sub
    Private Sub InitStylesPriority()
        CheckCode_Script.ClearStylesBuffer()
        'add this style explicitly for drawing under other styles
        CheckCode_Script.AddStyle(SameWordsStyle)
    End Sub
    Private Sub CBCodeMode_SelectedValueChanged(sender As Object, e As EventArgs) Handles CBCodeMode.SelectedValueChanged
        If (CBCodeMode.SelectedIndex = 0) Then
            CheckCode_Script.Language = FastColoredTextBoxNS.Language.VB
        Else
            CheckCode_Script.Language = FastColoredTextBoxNS.Language.JS
        End If
    End Sub

    Private Sub SystemSet_Resize(sender As Object, e As EventArgs) Handles Me.Resize

    End Sub

    Private Sub CheckCode_Script_TextChanged(sender As Object, e As TextChangedEventArgs) Handles CheckCode_Script.TextChanged
        If CBCodeMode.SelectedIndex > 0 Then
            CSharpSyntaxHighlight(e)
        End If
    End Sub
    Private Sub CSharpSyntaxHighlight(e As TextChangedEventArgs)

        CheckCode_Script.LeftBracket = "("
        CheckCode_Script.RightBracket = ")"
        CheckCode_Script.LeftBracket2 = "\x0"
        CheckCode_Script.RightBracket2 = "\x0"
        'clear style of changed range
        e.ChangedRange.ClearStyle(BlueStyle, BoldStyle, GrayStyle, MagentaStyle, GreenStyle, BrownStyle)

        'string highlighting
        e.ChangedRange.SetStyle(BrownStyle, """""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'")
        'comment highlighting
        e.ChangedRange.SetStyle(GreenStyle, "//.*$", RegexOptions.Multiline)
        e.ChangedRange.SetStyle(GreenStyle, "(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline)
        e.ChangedRange.SetStyle(GreenStyle, "(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline Or RegexOptions.RightToLeft)
        'number highlighting
        e.ChangedRange.SetStyle(MagentaStyle, "\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b")
        'attribute highlighting
        e.ChangedRange.SetStyle(GrayStyle, "^\s*(?<range>\[.+?\])\s*$", RegexOptions.Multiline)
        'class name highlighting
        e.ChangedRange.SetStyle(BoldStyle, "\b(class|struct|enum|interface)\s+(?<range>\w+?)\b")
        'keyword highlighting
        e.ChangedRange.SetStyle(BlueStyle, "\b(abstract|function|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b|#region\b|#endregion\b")

        'clear folding markers
        e.ChangedRange.ClearFoldingMarkers()
        'set folding markers
        e.ChangedRange.SetFoldingMarkers("{", "}") 'allow to collapse brackets block
        e.ChangedRange.SetFoldingMarkers("#region\b", "#endregion\b") 'allow to collapse #region blocks
        e.ChangedRange.SetFoldingMarkers("/\*", "\*/") 'allow to collapse comment block
    End Sub

End Class